#include <iostream>
#include <pthread.h>
#include <unistd.h>

int cnt = 0;

using namespace std;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* Count(void* arg)
{
    pthread_detach(pthread_self());     //分离线程
    uint64_t number = *(static_cast<uint64_t*>(arg));       //传值赋值，防止后续i改变造成的影响
    std::cout << "pthread: " << number << " create success" << std::endl;

    while (true)
    {
        pthread_mutex_lock(&mutex);
            //等待条件变量，直到被唤醒。
        pthread_cond_wait(&cond, &mutex);     //？ 为什么在这里？ 1. pthread_cond_wait让线程等待的时候，会自动释放锁！

        std::cout << "pthread: " << number << " ， cnt: " << cnt++ << std::endl;    //全局变量是一个临界资源
        pthread_mutex_unlock(&mutex);
    }

}

int main()
{
    for (uint64_t i = 0; i < 5; i++)
    {
        pthread_t tid;
        pthread_create(&tid, nullptr, Count, (void*)&i);
        usleep(1000);
    }

    sleep(3);       //保证线程全部创建完成
    std::cout << "main thread ctrl begin: " << std::endl;

    while (true)
    {
        sleep(1);
        //pthread_cond_signal(&cond);     //唤醒在cond的等待队列中等待的一个线程，默认都是第一个
        pthread_cond_broadcast(&cond);     //唤醒在cond的等待队列中等待的所有线程

        std::cout << "signal one thread..." << std::endl;
    }

    return 0;
}